package com.panvan.android;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.RemoteException;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;

import androidx.core.app.NotificationCompat;

import com.panvan.android.BuildConfig;
import com.panvan.android.R;

import java.util.HashMap;
import java.util.Map;

public class WebViewJsBridge {

    MainActivity activity;
    WebViewJsBridge(MainActivity activity){
        this.activity=activity;

    }

    /**
     * 判断是否可以建立通讯
     * @return
     */
    @JavascriptInterface
    public boolean isConnection(){
        return true;
    }

    /**
     * 刷新webView
     */
    @JavascriptInterface
    public void webViewReload(){
        try{
            this.activity.mainView.evaluateJavascript("javascript:window.location.href='"+ BuildConfig.MAIN_URL+"'", new ValueCallback<String>() {
                //此处为 js 返回的结果
                @Override
                public void onReceiveValue(String value) {}
            });
        }catch(Exception e){}
    }


    /**
     * 获取系统基座信息
     * @return
     */
    @JavascriptInterface
    public String getSystemInfo() {
        Map map = new HashMap();
        map.put("DEBUG", BuildConfig.DEBUG);
        map.put("APPLICATION_ID", BuildConfig.APPLICATION_ID);
        map.put("BUILD_TYPE", BuildConfig.BUILD_TYPE);
        map.put("VERSION_CODE", BuildConfig.VERSION_CODE);
        map.put("VERSION_NAME", BuildConfig.VERSION_NAME);
        map.put("APP_NAME", BuildConfig.APP_NAME);
        map.put("ERROR_PATH", BuildConfig.ERROR_PATH);
        map.put("MAIN_URL", BuildConfig.MAIN_URL);
        map.put("WEB_VIEW_CAN_BACK", BuildConfig.WEB_VIEW_CAN_BACK);
        map.put("WELCOME_TEXT", BuildConfig.WELCOME_TEXT);

        return map.toString();
    }

    /**
     * 播放提示音
     */
    MediaPlayer mediaPlayer;


    @JavascriptInterface
    public boolean playPromptSound(){
        return this.playPromptSound(null);
    }
    @JavascriptInterface
    public boolean playPromptSound(String videoUrl) {
        try {
            if (videoUrl == null) {
                mediaPlayer = MediaPlayer.create(activity, R.raw.y682);
                mediaPlayer.start();
            } else {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDataSource(videoUrl);
                mediaPlayer.prepare();//prepare之后自动播放
            }
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer player) {
                    player.stop();
                    player.release();
                }
            });
            mediaPlayer.start();
            return true;
        } catch (Exception e) {
            if (BuildConfig.BUILD_TYPE.equals("debug")) {
                throw new RuntimeException(e);
            }
            return false;
        }
    }

    @JavascriptInterface

    public boolean cancelPromptSound() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
            }
            return true;
        } catch (Exception e) {
            if (BuildConfig.BUILD_TYPE.equals("debug")) {
                throw new RuntimeException(e);
            }
            return false;
        }
    }


    /**
     * 让手机震动
     * @param isUninterrupted 是否连续震动，还是震动一次
     * @param pattern
     * @return
     */
    @JavascriptInterface
    public boolean playVibrator(boolean isUninterrupted,long [] pattern) {
        try {
            if (isUninterrupted==true) {
                if (pattern == null) {
                    long[] _pattern = {1000, 1000, 2000, 50};
                    pattern = _pattern;
                }
                if (this.activity.vibrator.hasVibrator()) {
                    this.activity.vibrator.vibrate(pattern, -1);
                }
            } else {
                if (this.activity.vibrator.hasVibrator()) {
                    this.activity.vibrator.vibrate(pattern == null || pattern.length <= 0 ? 1000 : pattern[0]);
                }
            }
            return true;
        } catch (Exception e) {
            if (BuildConfig.BUILD_TYPE.equals("debug")) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    /**
     * 停止手机震动
     */
    @JavascriptInterface

    public boolean cancelVibrator(){
        try{
            if(this.activity.vibrator!=null){
                this.activity.vibrator.cancel();
            }
        }catch(Exception e){
            return false;
        }
        return true;
    }

    /**
     * 启动其他App
     * @param packageName
     */
    @JavascriptInterface
    public void startApp(String packageName) {
        try {
            Intent LaunchIntent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
            activity. startActivity(LaunchIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载文件
     * @param url 文件地址
     */
    @JavascriptInterface
    public void downloadFile(String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            activity.startActivity(intent);
        } catch (Exception e) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse(url));
            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            activity.startActivity(intent);
        }
    }


    /**
     * 退出系统
     * @param isShowConfirmBox 是否显示退出对话框
     * @param isForcibly 是否强制退出
     */
    @JavascriptInterface
    public void exitSystem(boolean isShowConfirmBox,boolean isForcibly){
        if(!isShowConfirmBox){
            exitSystemActivity(isForcibly);
            return;
        }
        new AlertDialog.Builder(activity)
            .setMessage("是否要退出当前应用?").setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    exitSystemActivity(isForcibly);
                }
            })
            .setNegativeButton("否", null)
            .show();
    }

    /**
     * 设置当前音量
     * @param volume 音量
     * @param type 0 通话 , 1 系统 , 2 铃声  , 3 音乐回放即媒体音量  , 4 警报
     */
    @JavascriptInterface
    public void setAudioVolume(int volume,int type) {
        try {
            if (type <= 0 || type > 4) {
                type = 3;
            }
            int[] types = new int[]{
                    AudioManager.STREAM_VOICE_CALL, //通话
                    AudioManager.STREAM_SYSTEM, //系统
                    AudioManager.STREAM_RING,//铃声
                    AudioManager.STREAM_MUSIC, //音乐回放即媒体音量
                    AudioManager.STREAM_ALARM //警报
            };


            //获取系统的Audio管理者
            AudioManager mAudioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
            //当前音量
            mAudioManager.setStreamVolume(types[type], volume, 0);
        } catch (Exception e) {
        }
    }

    /**
     * 获取当前音量
     */
    @JavascriptInterface
    public int getMaxAudioVolume() {
        try {
            //获取系统的Audio管理者
            AudioManager mAudioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
            //最大音量
            return mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            return -1;
        }
    }

















    /**
     * 退出系统
     * @param isForcibly 是否强制退出
     */
    public void exitSystemActivity(boolean isForcibly){
        if(isForcibly){
            System.exit(0);
            return;
        }
        activity.finish();
    }







    @JavascriptInterface
    public void wakeLockOpen(long wakeTime){
        activity.wakeLockOpen(wakeTime);
    }

    @JavascriptInterface
    public void wakeLockClose(){
        activity.wakeLockClose();
    }













    public  NotificationCompat.Builder builder =null;
    private int COUNT_ID=94010241;
    public  NotificationManager mNotificationManager=null;
    private  String CHANNEL_ID;

    /**
     * 发送notify 本地消息推送
     * @param title
     * @param text
     * @return
     */
    @JavascriptInterface
    public boolean showNotify(String title, String text){
        if(mNotificationManager==null){
            mNotificationManager=(NotificationManager)activity.getSystemService(Context.NOTIFICATION_SERVICE);
            CHANNEL_ID=createNotificationChannel();
            builder =  new NotificationCompat.Builder(activity, CHANNEL_ID);
        }
        try{

            activity.wakeLockOpen();
//            Uri uri=this.getNotifySound();
            Intent intent= activity.getIntent();
            COUNT_ID++;


            PendingIntent pendingIntent;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                pendingIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_IMMUTABLE);
            } else {
                pendingIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            }
            builder
//                    .setSound(uri)
                    .setSmallIcon(R.drawable.logo)
                    .setContentTitle(title)
                    .setContentText(text) //收到通知时的效果，这里是默认声音
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
            mNotificationManager.notify(COUNT_ID, builder.build());
        }catch(Exception e){
            if(BuildConfig.BUILD_TYPE.equals("debug")){
                e.printStackTrace();
            }
            return false;
        }
        return true;
    }

    /**
     * 获取channel_id
     */
    public  String createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String NOTIFY_CHANNEL = BuildConfig.APPLICATION_ID+"MY_CHANNEL_CALL_LEND_STOCK"; //确保唯一
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(NOTIFY_CHANNEL, "Notifications", importance);
            channel.setDescription("This is a notification channel");

            Uri uri=getNotifySound();
            channel.setSound(uri,  Notification.AUDIO_ATTRIBUTES_DEFAULT );
            NotificationManager  notificationManager = (NotificationManager)activity.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
            return NOTIFY_CHANNEL;
        }
        return "";
    }

    public Uri getNotifySound(){
//        String packageName=BuildConfig.APPLICATION_ID;
        return getResourceUri(R.raw.y682);
//        return Uri.parse("android:resource://"+packageName+"/R.raw.y682");
    }



    private Uri getResourceUri(Integer model) {
        Resources resources=activity.getResources();
        try {
            return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                    + resources.getResourcePackageName(model) + '/'
                    + resources.getResourceTypeName(model) + '/'
                    + resources.getResourceEntryName(model));
        } catch (Resources.NotFoundException e) {
            return null;
        }
    }
}
